import { defineStore } from "pinia";
import { StsState } from "@/stores/interface";
import { Upload } from "@/api/interface/upload";
import { getFlatArr, getShowMenuList, getAllBreadcrumbList } from "@/utils/util";
import { homeRouter } from "@/routers/modules/staticRouter";
import { getConfig, followUp } from "@/api/modules/upload";
// Upload.File.OssConfig
import { ElSkeleton } from "element-plus";
import OSS from "ali-oss";

type SuccessFunc =  ((oss_config: Upload.File.OssConfig | undefined) => void) | undefined;
// AuthStore
export const StStore = defineStore({
	id: "Sts",
	state: (): StsState => ({
		oss: undefined,
		upload: undefined,
		dir_prefix:undefined,
		timeOut: undefined,
		admins_id:undefined,
		capacity:undefined,
		max_capacity:undefined
	}),
	getters: {
		// 按钮权限列表
		uploadConfigGet: state => state.upload,
		ossConfigGet: state => state.oss,
		dirPrefixGet: state => state.dir_prefix,
		capacityGet: state => state.capacity,
		maxCapacityGet: state => state.max_capacity,
		// // 后端返回的菜单列表 ==> 这里没有经过任何处理
		// accessKeySecretGet: state => state.accessKeySecret,
		// // 后端返回的菜单列表 ==> 左侧菜单栏渲染，需要去除 isHide == true
		// ossBucketGet: state => state.oss_bucket,
		// // 扁平化之后的一维数组路由，主要用来添加动态路由
		// securityTokenGet: state => state.securityToken,
		// // 所有面包屑导航列表
		// timeoutGet: state => state.timeout,

		// ossStartGet: state => state.oss_start
	},
	actions: {

	 setCapacity(capacity:number,max_capacity:number){
      this.capacity = capacity;
			this.max_capacity = max_capacity;
	 },

		async loadConfig(successFunc: SuccessFunc = undefined) {
			if (this.timeOut) clearTimeout(this.timeOut);
			await this.reqConfig(true, successFunc);
		},


		async reqConfig(loading: boolean = true, successFunc: SuccessFunc = undefined) {
			const res = await getConfig(loading);
			this.oss = res.data.oss;
			this.upload = res.data.upload;
			this.dir_prefix = res.data.dir_prefix;
			this.admins_id = res.data.admins_id;
			if (successFunc) successFunc(this.oss);
			if (res.data.oss?.timeout){
				this.resetTimeOut(successFunc);
			} 
			else clearTimeout(this.timeOut);
		},

		async resetTimeOut(successFunc: SuccessFunc = undefined) {

			if (!this.oss?.timeout) return;

			if (Math.floor((new Date).getTime() / 1000) >= this.oss.timeout) await this.reqConfig(false, successFunc);
			else {

				this.timeOut = setTimeout(() => {

					this.resetTimeOut(successFunc);

				}, 1000);

			}
		},

		getImgConfig(){
			return this.uploadConfigGet?.upload_file_type[0].type ? this.uploadConfigGet?.upload_file_type[0].type : "";
		}

		// createOssUrl(uuid: string , dir_id:string ,is_common : 1|0 , file_type:string ){
		// 	let file = `${dir_id}/${uuid}${file_type ? '.'+file_type : ''}`;
		// 	return is_common === 0 ? `/${this.dir_prefix?.admins}/${this.admins_id}/${file}` : `/${this.dir_prefix?.common}/${file}` ;
		// }
		

	}
});
